package org.ysu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.ysu.common.JsonResult;
import org.ysu.mapper.FamilyMapper;
import org.ysu.mapper.PoorMapper;
import org.ysu.mapper.VCadreMapper;
import org.ysu.pojo.*;
import org.ysu.service.InterviewService;
import org.ysu.mapper.InterviewMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author libaoyu
* @description 针对表【interview】的数据库操作Service实现
* @createDate 2024-06-17 14:59:48
*/
@Service
public class InterviewServiceImpl extends ServiceImpl<InterviewMapper, Interview>
    implements InterviewService{
    @Resource
    private InterviewMapper interviewMapper;

    @Autowired
    private PoorMapper poorMapper;

    @Autowired
    private FamilyMapper familyMapper;
    @Autowired
    private VCadreMapper vCadreMapper;

    /**
     * 用户id查询走访记录
     * @param id
     * @return
     */
    @Override
    public InterViewList getInterviewByid (Integer id){
        LambdaQueryWrapper<Interview> wrapper=new LambdaQueryWrapper<>();
        if(id!=0){
            wrapper.eq(Interview::getVcId,id);
        }else{
            wrapper.ge(Interview::getVcId,1);
        }
        //查询所有走访记录按时间降序排列
        List<Interview> interviews=interviewMapper.selectList(wrapper);
        interviews.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));
        InterViewList interViewList=new InterViewList();
        List<String> names=new ArrayList<>();
        List<Integer> ids=new ArrayList<>();
        List<InterViewFull> interViewFulls=new ArrayList<>();
        //获取更多对象信息
        for(Interview interview:interviews){
            InterViewFull interViewFull=new InterViewFull();
            interViewFull.setInterview(interview);
            Poor poor = poorMapper.getPoor(interview.getPId());
            ids.add(interview.getPId());
            Family family = familyMapper.getFamily(interview.getFId());
            VCadre vCadre = vCadreMapper.getVCadre(interview.getVcId());
            interViewFull.setPoor(poor);
            interViewFull.setFamily(family);
            interViewFull.setVc(vCadre);
            //加入interViewList
            interViewFulls.add(interViewFull);
        }
        //names和ids列表去除重复内容
        ids=ids.stream().distinct().collect(Collectors.toList());
        for(Integer idt :ids){
            names.add(poorMapper.getPoorName(idt));
        }
        interViewList.setList(interViewFulls);
        interViewList.setPoorNames(names);
        interViewList.setPIds(ids);
        interViewList.setCount(interviews.size());
        return interViewList;
    }

    @Override
    public Integer addInterview(Interview interview){
        //判断是否有返贫风险
        BigDecimal MIN_INCOME = new BigDecimal(2300);
        if(interview.getIncome().compareTo(MIN_INCOME)<0){
            int fid=interview.getFId();
            familyMapper.setPovertyById(fid,1);
        }
        return interviewMapper.insert(interview);
    }

    @Override
    public JsonResult uploadAvatar(byte[] bytes, Integer id) {
        return interviewMapper.uploadAvatar(bytes,id);
    }

    @Override
    public InterViewList getInterviewsByPara(InterviewForm interviewForm) {
        //在interview表中查询，如果interviewForm条件不为null，则查询条件
        LambdaQueryWrapper<Interview> wrapper=new LambdaQueryWrapper<>();
        //如果starttime不为空找到starttime开始的记录
        //如果endtime不为空，找到endtime截至的记录
        if(interviewForm.getStartTime()!=null){
            wrapper.ge(Interview::getTime,interviewForm.getStartTime());
        }
        if(interviewForm.getEndTime()!=null){
            wrapper.le(Interview::getTime,interviewForm.getEndTime());
        }
        if(interviewForm.getPId()!=null){
            wrapper.eq(Interview::getPId,interviewForm.getPId());
        }
        if(interviewForm.getId()!=null){
            wrapper.eq(Interview::getVcId,interviewForm.getId());
        }
        List<Interview> interviews=interviewMapper.selectList(wrapper);
        InterViewList interViewList=new InterViewList();
        List<String> names=new ArrayList<>();
        List<Integer> ids=new ArrayList<>();
        List<InterViewFull> interViewFulls=new ArrayList<>();
        for(Interview interview:interviews){
            InterViewFull interViewFull=new InterViewFull();
            interViewFull.setInterview(interview);
            Poor poor = poorMapper.getPoor(interview.getPId());
            ids.add(interview.getPId());
            Family family = familyMapper.getFamily(interview.getFId());
            VCadre vCadre = vCadreMapper.getVCadre(interview.getVcId());
            interViewFull.setPoor(poor);
            interViewFull.setFamily(family);
            interViewFull.setVc(vCadre);
            interViewFulls.add(interViewFull);
        }
        ids=ids.stream().distinct().collect(Collectors.toList());
        for(Integer id:ids){
            names.add(poorMapper.getPoorName(id));
        }
        interViewList.setList(interViewFulls);
        interViewList.setPoorNames(names);
        interViewList.setPIds(ids);
        interViewList.setCount(interviews.size());
        return interViewList;
    }

    @Override
    public Statistics getInomeAndLiability(Integer id, Integer data) {
        // 获取当前日期
        Date endDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String endTime = dateFormat.format(endDate);

        // 使用 Calendar 进行日期减法
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(endDate);
        calendar.add(Calendar.DAY_OF_MONTH, -data + 1);
        Date startDate = calendar.getTime();
        String startTime = dateFormat.format(startDate);

//        计算天数
        Statistics statistics=new Statistics();

        LambdaQueryWrapper<Interview> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Interview::getFId,id)
                .between(Interview::getTime,startTime+" 00:00:00",endTime+" 23:59:59")
                .orderByAsc(Interview::getTime);
        List<Interview> interviews = interviewMapper.selectList(wrapper);

        // 统计每个风险每次的变化情况
        // 0:收入；1：负债
        Map<Integer, Map<String, Integer>> records = new HashMap<>();
        for(int i=0;i<2;i++){
            records.put(i, new HashMap<>());
        }
        Map<String, Integer> dateRange1 = new HashMap<>();
        for (Interview interview : interviews) {
            Date interviewDate = interview.getTime(); // 获取记录的日期
            String interviewDate1 = dateFormat.format(interviewDate); //转格式
            if(dateRange1.containsKey(interviewDate1)){
                continue;
            }
            Integer income=interview.getIncome().intValue();
            Integer liability=interview.getLiability().intValue();
            // 更新hash表数据
            for(int i=0;i<2;i++){
                switch (i){
                    case 0:
                        records.get(i).put(interviewDate1,income);
                        break;
                    case 1:
                        records.get(i).put(interviewDate1,liability);
                        break;
                    default:
                        break;
                }
            }
            dateRange1.put(interviewDate1,1);
        }
        // 将结果整理为二维数组
        List<String> names = new ArrayList<>();
        names.add("收入");
        names.add("负债");
        List<Date> dateRange = new ArrayList<>();
        for (int i = 0; i < data; i++) {
            Date date = calendar.getTime();
            dateRange.add(date);
            calendar.add(Calendar.DAY_OF_MONTH, +1);
        }
        Integer[][] counts = new Integer[records.size()][data];
        int personIndex = 0;
        for (Map.Entry<Integer, Map<String, Integer>> entry : records.entrySet()) {

            Map<String, Integer> record2 = entry.getValue();

            int dateIndex = 0;
            for (Date date : dateRange) {
                String dateString = dateFormat.format(date);
                counts[personIndex][dateIndex] = 0;
                if(record2.get(dateString)!=null){
                    counts[personIndex][dateIndex] = record2.get(dateString);
                }
                dateIndex++;
            }
            personIndex++;
        }
        statistics.setNames(names);
        statistics.setCounts(counts);
        return statistics;
    }

}




